import React, { useState, useEffect, useCallback } from 'react'
import { Mic, MicOff, Send, Trash2, Volume2, Settings } from 'lucide-react'
import { useVoiceStore } from '../stores/voiceStore'
import { useDeviceStore } from '../stores/deviceStore'
import { useSocketStore } from '../stores/socketStore'
import speechService from '../services/speechService'
import { vibrate } from '../utils/device'
import { diagnoseMismatchedStates, autoFixStateMismatches, resetAllStates } from '../utils/stateSync'
import { useStreamingSpeechRecognition } from '../hooks/useStreamingSpeechRecognition';

// 类型定义
interface DebugInfo {
  pairingStatus: 'pairing' | 'paired' | 'unpaired'
  pairedDevicesCount: number
  pairedDevices: any[]
  currentSession: string | null
  deviceId: string | null
  isRegistered: boolean
  isConnected: boolean
  timestamp: string
}

interface VoiceResult {
  success: boolean
  text?: string
  confidence?: number
  error?: string
}

interface VoiceError {
  message: string
}

const VoiceInputPage: React.FC = () => {
  const [isInitialized, setIsInitialized] = useState<boolean>(false)
  const [initError, setInitError] = useState<string | null>(null)
  const [useServerRecognition, setUseServerRecognition] = useState<boolean>(true)
  const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | null>(null)
  const [debugInfo, setDebugInfo] = useState<DebugInfo>({} as DebugInfo)

  const {
    isRecording,
    isProcessing,
    recognitionText,
    finalText,
    confidence,
    language,
    error,
    voiceHistory,
    settings,
    audioUrl,
    startRecording,
    stopRecording,
    setRecognitionText,
    setError,
    clearError,
    reset,
    getRecordingStatus,
    getFormattedDuration,
    getCurrentText,
    setAudioData,
    clearHistory
  } = useVoiceStore()

  const { deviceId, isRegistered, registerDevice, user } = useDeviceStore()
  const { emit, isConnected, socket } = useSocketStore()

  const { devices, fetchDevices } = useDeviceStore()
  const [selectedDevice, setSelectedDevice] = useState<string>('')
  const [showDeviceSelect, setShowDeviceSelect] = useState(false)

  // 移除 pairingStatus, pairedDevices, 相关 useEffect、UI 提示
  // 监听配对状态变化，配对成功后自动刷新页面
  // 移除 getPairingStatus 相关 useRef 和 useEffect

  // 确保设备已注册的函数
  const ensureDeviceRegistered = useCallback(async (): Promise<void> => {
    if (!isConnected || !socket) {
      throw new Error('Socket未连接')
    }
    
    if (!isRegistered) {
      console.log('📱 设备未注册，开始注册...')
      try {
        await registerDevice(socket)
        console.log('✅ 设备注册成功')
      } catch (error) {
        console.error('❌ 设备注册失败:', error)
        throw new Error('设备注册失败: ' + (error as Error).message)
      }
    } else {
      console.log('✅ 设备已注册，跳过注册')
    }
  }, [isConnected, socket, isRegistered, registerDevice])

  // 页面加载时确保设备已注册
  useEffect(() => {
    const autoRegisterDevice = async () => {
      if (isConnected && socket && !isRegistered) {
        try {
          console.log('🎤 VoiceInputPage: 自动注册设备...')
          await ensureDeviceRegistered()
        } catch (error) {
          console.error('❌ VoiceInputPage: 自动注册设备失败:', error)
        }
      }
    }

    autoRegisterDevice()
  }, [isConnected, socket, isRegistered, ensureDeviceRegistered])

  // 初始化语音识别
  useEffect(() => {
    const initSpeech = async () => {
      try {
        if (useServerRecognition) {
          // 服务端识别模式：初始化媒体录制
          console.log('🎤 初始化服务端语音识别模式')
          
          const stream = await navigator.mediaDevices.getUserMedia({ 
            audio: {
              echoCancellation: settings.echoCancellation,
              noiseSuppression: settings.noiseReduction,
              autoGainControl: settings.autoGainControl,
              sampleRate: 16000
            } 
          })
          
          const recorder = new MediaRecorder(stream, {
            mimeType: 'audio/webm;codecs=opus'
          })
          
          setMediaRecorder(recorder)
          console.log('✅ 媒体录制器初始化成功')
          
        } else {
          // 客户端识别模式：初始化Web Speech API
          console.log('🎤 初始化客户端语音识别模式')
          
          if (!speechService.supported) {
            throw new Error('当前浏览器不支持语音识别')
          }

          // 请求麦克风权限
          await speechService.requestMicrophonePermission()

          // 初始化语音识别
          speechService.initialize({
            language,
            continuous: settings.continuous,
            interimResults: settings.interimResults,
            maxAlternatives: settings.maxAlternatives
          })
        }

        setIsInitialized(true)
        setInitError(null)
      } catch (error) {
        console.error('语音识别初始化失败:', error)
        setInitError((error as Error).message)
      }
    }

    initSpeech()
  }, [language, settings, useServerRecognition])

  // 集成流式语音识别 Hook
  const streamingRecognition = useStreamingSpeechRecognition({
    language,
    autoSend: settings.autoSend,
    onFinalResult: (text) => handleSendText(text)
  });

  // 开始录音
  const handleStartRecording = useCallback(async (): Promise<void> => {
    if (!isInitialized || isRecording) return

    try {
      clearError()

      // 在开始录音前确保设备已注册
      if (!isRegistered) {
        console.log('🎤 设备未注册，开始录音前先注册设备...')
        try {
          await ensureDeviceRegistered()
        } catch (error) {
          setError('设备注册失败，无法开始录音: ' + (error as Error).message)
          return
        }
      }

      startRecording()
      vibrate(50) // 震动反馈

      // 通知配对设备开始录音
      if (isConnected && isRegistered) {
        emit('voice:start', {
          timestamp: Date.now(),
          language,
          recognitionMode: useServerRecognition ? 'server' : 'client'
        })
      }

      if (useServerRecognition) {
        // 服务端流式识别模式
        streamingRecognition.start()
      } else {
        // 客户端识别模式：启动Web Speech API
        console.log('🎤 启动客户端语音识别...')
        speechService.start({
          onResult: (result) => {
            console.log('收到语音识别结果:', result)
            setRecognitionText(
              result.text,
              result.isFinal,
              result.confidence
            )
          },
          onError: (error) => {
            console.error('语音识别错误:', error)
            setError(error.message)
            stopRecording()
          },
          onEnd: () => {
            console.log('语音识别结束')
            if (isRecording) {
              handleStopRecording()
            }
          }
        })
      }

    } catch (error) {
      setError((error as Error).message)
      stopRecording()
    }
  }, [isInitialized, isRecording, clearError, startRecording, isConnected, isRegistered, language, useServerRecognition, mediaRecorder, setAudioData, ensureDeviceRegistered, setError, streamingRecognition])

  // 停止录音
  const handleStopRecording = useCallback((): void => {
    if (!isRecording) return

    console.log('停止录音...')
    
    if (useServerRecognition) {
      // 服务端流式识别模式
      streamingRecognition.stop()
    } else {
      // 客户端识别模式：停止Web Speech API
      speechService.stop()
    }
    
    stopRecording()
    vibrate([50, 50, 50]) // 震动反馈

    // 设置超时处理，防止一直处理中
    setTimeout(() => {
      const { isProcessing } = useVoiceStore.getState()
      if (isProcessing) {
        console.log('语音识别超时，重置状态')
        useVoiceStore.setState({ isProcessing: false })
      }
    }, 10000) // 服务端识别可能需要更长时间

    // 只有客户端识别模式才需要立即发送结果
    if (!useServerRecognition && isConnected && isRegistered) {
      const text = getCurrentText()
      if (text) {
        emit('voice:end', {
          text,
          confidence,
          timestamp: Date.now(),
          language
        })

        // 如果设置了自动发送，直接发送文字
        if (settings.autoSend) {
          setTimeout(() => {
            // 直接在这里发送文字，避免引用问题
            emit('text:input', {
              text,
              timestamp: Date.now(),
              language
            })
            vibrate(100)
            reset()
          }, 500) // 延迟发送，给用户看到结果的时间
        }
      } else {
        emit('voice:end', {
          timestamp: Date.now()
        })
      }
    }
  }, [isRecording, stopRecording, isConnected, isRegistered, emit, getCurrentText, confidence, language, settings.autoSend, useServerRecognition, mediaRecorder, reset, streamingRecognition])

  // 发送文字
  const handleSendText = useCallback((text: string): void => {
    if (!text || !isConnected || !isRegistered) return

    emit('text:input', {
      text,
      timestamp: Date.now(),
      language
    })

    vibrate(100) // 发送成功震动反馈
    reset() // 重置状态
  }, [isConnected, isRegistered, emit, language, reset])

  // 监听服务端识别结果
  useEffect(() => {
    if (!isConnected) {
      console.log('🔍 VoiceInputPage: Socket未连接，跳过设置语音识别监听器')
      return
    }
    
    console.log('🔍 VoiceInputPage: 设置语音识别结果监听器...')
    
    // 监听服务端识别结果
    const handleVoiceResult = (data: VoiceResult) => {
      console.log('📥 收到服务端识别结果:', data)
      
      if (data.success) {
        console.log('✅ 语音识别成功，设置文本:', data.text)
        setRecognitionText(data.text || '', true, data.confidence || 0.8)
        
        // 如果设置了自动发送，发送识别结果
        if (settings.autoSend && data.text) {
          console.log('🚀 自动发送识别结果:', data.text)
          setTimeout(() => handleSendText(data.text!), 500)
        }
      } else {
        console.error('❌ 语音识别失败:', data.error)
        setError(data.error || '服务端语音识别失败')
      }
    }
    
    const handleVoiceError = (data: VoiceError) => {
      console.error('❌ 服务端识别错误:', data)
      setError(data.message || '语音识别失败')
    }
    
    const socketInstance = useSocketStore.getState().socket;
    let cleanup: (() => void) | undefined;
    let debugHandler: ((eventName: string, ...args: any[]) => void) | undefined;
    if (socketInstance) {
      console.log('📝 添加语音识别事件监听器到socket:', socketInstance.id)
      // 先移除可能存在的监听器
      if (typeof (socketInstance as any).off === 'function') {
        (socketInstance as any).off('voice:result')
        (socketInstance as any).off('voice:error')
      }
      // 添加新的监听器
      if (typeof (socketInstance as any).on === 'function') {
        (socketInstance as any).on('voice:result', handleVoiceResult)
        (socketInstance as any).on('voice:error', handleVoiceError)
      }
      // 添加调试监听器，监听所有事件
      debugHandler = (eventName: string, ...args: any[]) => {
        if (eventName.startsWith('voice:')) {
          console.log(`🔍 [VoiceInputPage] 收到事件: ${eventName}`, args)
        }
      }
      // 使用onAny监听所有事件（如果可用）
      if (typeof (socketInstance as any).onAny === 'function') {
        (socketInstance as any).onAny(debugHandler)
      }
      console.log('📝 已设置服务端识别结果监听器')
      cleanup = () => {
        console.log('📝 清理语音识别结果监听器')
        if (typeof (socketInstance as any).off === 'function') {
          (socketInstance as any).off('voice:result', handleVoiceResult)
          (socketInstance as any).off('voice:error', handleVoiceError)
        }
        if (typeof (socketInstance as any).offAny === 'function' && debugHandler) {
          (socketInstance as any).offAny(debugHandler)
        }
      }
    } else {
      console.error('❌ VoiceInputPage: 无法获取socket实例')
    }
    return cleanup;
  }, [isConnected, setRecognitionText, setError, settings.autoSend, handleSendText])

  // 语音识别后弹出设备选择
  useEffect(() => {
    if (finalText) {
      fetchDevices()
      setShowDeviceSelect(true)
    }
  }, [finalText, fetchDevices])

  // 同步文字到设备
  const handleSyncToDevice = async () => {
    if (!selectedDevice) return
    if (!user?.token) {
      alert('未登录，无法同步')
      return
    }
    try {
      const res = await fetch(`/api/devices/${selectedDevice}/sync-text`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + user.token
        },
        body: JSON.stringify({ text: finalText })
      })
      if (!res.ok) throw new Error('同步失败')
      alert('同步成功！')
    } catch (e: any) {
      alert('同步失败: ' + e.message)
    }
    setShowDeviceSelect(false)
    setSelectedDevice('')
    reset()
  }

  // 清除当前文字
  const handleClearText = (): void => {
    reset()
  }

  // 重新录音
  const handleRetry = (): void => {
    reset()
    setTimeout(() => {
      handleStartRecording()
    }, 100)
  }

  const recordingStatus = getRecordingStatus()
  const currentText = getCurrentText()
  
  // 调试信息：跟踪currentText的变化
  useEffect(() => {
    console.log('🔍 VoiceInputPage: currentText变化:', {
      currentText,
      finalText,
      recognitionText,
      isRecording,
      isProcessing
    })
  }, [currentText, finalText, recognitionText, isRecording, isProcessing])

  // 如果没有配对设备，显示提示
  // 移除 pairingStatus !== 'paired' 的提示
  // 移除 pairingStatus !== 'paired' 的 UI 提示

  // 如果初始化失败，显示错误信息
  if (initError) {
    return (
      <div className="min-h-screen bg-gray-50 p-4 flex items-center justify-center">
        <div className="max-w-md mx-auto text-center">
          <div className="card bg-red-50 border-red-200">
            <div className="flex items-center justify-center w-16 h-16 mx-auto mb-4 bg-red-100 rounded-full">
              <Mic className="w-8 h-8 text-red-500" />
            </div>
            <h2 className="text-xl font-semibold text-red-800 mb-2">
              语音识别初始化失败
            </h2>
            <p className="text-red-600 mb-4">
              {initError}
            </p>
            <button
              onClick={() => window.location.reload()}
              className="btn btn-red"
            >
              重新加载
            </button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 p-4">
      <div className="max-w-md mx-auto space-y-4">
        
        {/* 识别模式切换 */}
        <div className="card">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-gray-700">识别模式</span>
            <div className="flex space-x-2">
              <button
                onClick={() => setUseServerRecognition(false)}
                className={`px-3 py-1 text-xs rounded-full border ${
                  !useServerRecognition 
                    ? 'bg-blue-500 text-white border-blue-500' 
                    : 'bg-white text-gray-600 border-gray-300'
                }`}
              >
                客户端
              </button>
              <button
                onClick={() => setUseServerRecognition(true)}
                className={`px-3 py-1 text-xs rounded-full border ${
                  useServerRecognition 
                    ? 'bg-blue-500 text-white border-blue-500' 
                    : 'bg-white text-gray-600 border-gray-300'
                }`}
              >
                服务端
              </button>
            </div>
          </div>
          <div className="text-xs text-gray-500">
            {useServerRecognition ? '使用服务端进行语音识别（支持更多语言）' : '使用浏览器内置语音识别（更快响应）'}
          </div>
        </div>

        {/* 状态显示 */}
        <div className="card">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <div className={`w-3 h-3 rounded-full ${
                recordingStatus === 'recording' ? 'bg-red-500 animate-pulse' :
                recordingStatus === 'processing' ? 'bg-yellow-500 animate-pulse' :
                recordingStatus === 'error' ? 'bg-red-500' :
                'bg-green-500'
              }`} />
              <span className="text-sm font-medium">
                {recordingStatus === 'recording' && '正在录音...'}
                {recordingStatus === 'processing' && (useServerRecognition ? '服务端识别中...' : '处理中...')}
                {recordingStatus === 'error' && '出现错误'}
                {recordingStatus === 'idle' && '准备就绪'}
              </span>
            </div>
            <div className="text-xs text-gray-500">
              {getFormattedDuration()}
            </div>
          </div>
        </div>

        {/* 错误显示 */}
        {error && (
          <div className="card bg-red-50 border-red-200">
            <div className="flex items-start space-x-2">
              <div className="flex-shrink-0 w-5 h-5 text-red-500 mt-0.5">⚠️</div>
              <div className="flex-1">
                <div className="text-sm font-medium text-red-800">错误</div>
                <div className="text-sm text-red-600 mt-1">{error}</div>
              </div>
              <button
                onClick={clearError}
                className="flex-shrink-0 text-red-400 hover:text-red-600"
              >
                ✕
              </button>
            </div>
          </div>
        )}

        {/* 识别文本显示 */}
        <div className="card min-h-32">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-gray-700">识别文本</span>
            {currentText && (
              <button
                onClick={handleClearText}
                className="text-gray-400 hover:text-gray-600"
              >
                <Trash2 className="w-4 h-4" />
              </button>
            )}
          </div>
          
          <div className="min-h-20 p-3 bg-gray-50 rounded-lg border">
            {currentText ? (
              <div className="space-y-2">
                <div className="text-gray-900">
                  {finalText && (
                    <span className="font-medium">{finalText}</span>
                  )}
                  {recognitionText && recognitionText !== finalText && (
                    <span className="text-gray-600 ml-1">{recognitionText}</span>
                  )}
                </div>
                {confidence > 0 && (
                  <div className="text-xs text-gray-500">
                    置信度: {Math.round(confidence * 100)}%
                  </div>
                )}
              </div>
            ) : (
              <div className="text-gray-400 text-center py-4">
                {isRecording ? '正在监听...' : '点击麦克风开始录音'}
              </div>
            )}
          </div>
        </div>

        {/* 录音控制按钮 */}
        <div className="flex justify-center space-x-4">
          {!isRecording ? (
            <button
              onClick={handleStartRecording}
              disabled={!isInitialized || isProcessing}
              className={`flex items-center justify-center w-16 h-16 rounded-full text-white shadow-lg transition-all ${
                !isInitialized || isProcessing
                  ? 'bg-gray-400 cursor-not-allowed'
                  : 'bg-red-500 hover:bg-red-600 active:scale-95'
              }`}
            >
              <Mic className="w-8 h-8" />
            </button>
          ) : (
            <button
              onClick={handleStopRecording}
              className="flex items-center justify-center w-16 h-16 rounded-full bg-gray-500 hover:bg-gray-600 text-white shadow-lg transition-all active:scale-95"
            >
              <MicOff className="w-8 h-8" />
            </button>
          )}
        </div>

        {/* 操作按钮 */}
        {currentText && !isRecording && !isProcessing && (
          <div className="flex space-x-2">
            <button
              onClick={() => handleSendText(currentText)}
              className="flex-1 btn btn-primary"
            >
              <Send className="w-4 h-4 mr-2" />
              发送文字
            </button>
            
            <button
              onClick={handleRetry}
              className="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg border transition-colors"
            >
              <Mic className="w-4 h-4" />
            </button>
            
            {/* 播放录音按钮 */}
            {audioUrl && (
              <button
                onClick={() => {
                  const audio = new Audio(audioUrl)
                  audio.play()
                }}
                className="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg border transition-colors"
              >
                <Volume2 className="w-4 h-4" />
              </button>
            )}
          </div>
        )}

        {/* 历史记录 */}
        {voiceHistory.length > 0 && (
          <div className="card">
            <div className="flex items-center justify-between mb-3">
              <span className="text-sm font-medium text-gray-700">
                历史记录 ({voiceHistory.length})
              </span>
              <button
                onClick={() => clearHistory()}
                className="text-xs text-gray-400 hover:text-gray-600"
              >
                清空
              </button>
            </div>
            <div className="space-y-2 max-h-40 overflow-y-auto">
              {voiceHistory.slice().reverse().map((item) => (
                <div
                  key={item.id}
                  className="p-2 bg-gray-50 rounded border text-sm cursor-pointer hover:bg-gray-100"
                  onClick={() => {
                    setRecognitionText(item.text, true, item.confidence)
                  }}
                >
                  <div className="text-gray-900">{item.text}</div>
                  <div className="text-xs text-gray-500 mt-1">
                    {new Date(item.timestamp).toLocaleTimeString()} • 
                    置信度: {Math.round(item.confidence * 100)}%
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 设置快捷入口 */}
        <div className="flex justify-center">
          <button
            onClick={() => {
              // 这里可以打开设置页面或显示设置面板
              window.location.href = '/settings'
            }}
            className="flex items-center space-x-2 px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors"
          >
            <Settings className="w-4 h-4" />
            <span className="text-sm">设置</span>
          </button>
        </div>
      </div>
      {showDeviceSelect && finalText && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow p-6 w-full max-w-xs">
            <h3 className="text-lg font-bold mb-2">选择要同步的设备</h3>
            <select
              className="input w-full mb-4"
              value={selectedDevice}
              onChange={e => setSelectedDevice(e.target.value)}
            >
              <option value="">请选择设备</option>
              {devices.map(dev => (
                <option key={dev.id} value={dev.id} disabled={!dev.online}>
                  {dev.name} {dev.online ? '' : '(离线)'}
                </option>
              ))}
            </select>
            <button
              className="btn btn-primary w-full"
              onClick={handleSyncToDevice}
              disabled={!selectedDevice}
            >
              同步到设备
            </button>
            <button
              className="btn btn-secondary w-full mt-2"
              onClick={() => setShowDeviceSelect(false)}
            >
              取消
            </button>
          </div>
        </div>
      )}
    </div>
  )
}

export default VoiceInputPage 